var StartLayer = cc.Layer.extend({
    _ready: null,
    _tipSprite: null,
    _bird: null,
    _ground: null,
    _birdX: 0,
    _score: 0,
    _scoreSprite: null,
    _start: false,
    ctor: function(){
        this._super();
        if ('touches' in sys.capabilities) 
            this.setTouchEnabled(true);
        else if ('mouse' in sys.capabilities) 
            this.setMouseEnabled(true);
    },
    init: function(){
        var bRet = false;
        if (this._super()) {
            var winSize = cc.Director.getInstance().getWinSize();
            var _this = this;
            //背景
            var sp = cc.Sprite.create(config.getBackground(), cc.rect(0, 0, config.width, config.height));
            sp.setAnchorPoint(cc.p(0, 0));
            this.addChild(sp, 0, 1);
            
            //score
            var score = cc.Sprite.create();
            this._scoreSprite = score;
            this.addChild(score, 10, 1);
            
            //ready
            var ready = cc.Sprite.create(s_get_ready);
            this._ready = ready;
            ready.setPosition(winSize.width / 2, winSize.height / 2 + 80);
            this.addChild(ready, 10, 1);
            
            //鸟
            var num = config.birdType;
            var bird = cc.Sprite.create(s_bird(num));
            this._bird = bird;
            bird.setPosition(cc.p(winSize.width / 2 - 60, winSize.height / 2));
            this._birdX = bird.getPositionX();
            this.addChild(bird, 10, 1);
            bird.runAction(Animate.birdFly(num));
            bird.runAction(Animate.birdJump());
            
            //Tip
            var tip = cc.Sprite.create(s_tip);
            this._tipSprite = tip;
            tip.setPosition(winSize.width / 2, winSize.height / 2 - 20);
            this.addChild(tip, 1);
            
            //地面
            var ground = Ground.create();
            this._ground = ground;
            this.addChild(ground, 10);
            
            //管子
            this.addPipe();
			
			this.setScore();
            
            bRet = true;
        }
        return bRet;
    },
    onStart: function(){
        cc.log("--- Start ---");
        sound.playWingSound();
        this._start = true;
        this._bird.cleanup();
        this._bird.runAction(Animate.birdFly(config.birdType));
        
        this._ready.removeFromParent(true);
        this._tipSprite.removeFromParent(true);
        
        this.scheduleUpdate();
    },
    setScore: function(){
        var winSize = cc.Director.getInstance().getWinSize();
        var s = this._score + "", w = 0;
        this._scoreSprite.removeAllChildren(true);
        for (var i = 0; i < s.length; i++) {
            var num = cc.Sprite.create(s_b_font(s[i]));
            num.setPosition(i * 30, 0);
            w = i * 30 / 2;
            this._scoreSprite.addChild(num);
        }
        this._scoreSprite.setPosition(winSize.width / 2 - w, winSize.height / 2 + 160);
    },
    randomBottom: function(){
        var ran = Math.round(Math.random() * 380);
        if (ran < 30) {
            return 30;
        }
        if (ran > 370 - config.pipeOffsetY) {
            return 370 - config.pipeOffsetY;
        }
        return ran;
    },
    _crossFlag: false,
    _die: false,
    _t: 0,
	_v: 0,
    _in: true,
    _allOverFlag: false,
    update: function(){
        if (!this._die) {
            this._t++;
			this._v--;
            //鸟
            var bird = this._bird;
            var bPrePos = bird.getPositionY();
            bird.setPositionY(bPrePos - 0.1 * this._t + 0.1 * this._v);
            this._in = true;
            if (bPrePos <= 112) {
                bird.setPositionY(120);
                this._die = true;
            } else if (bPrePos > config.height) {
                this._in = false;
            }
            //管子
            var pa = this.pipeArray;
            for (i in pa) {
                var prePos = pa[i].b.getPositionX(), ran = this.randomBottom();
                if (prePos <= 0) {
                    prePos = config.pipeOffsetX * 3;
                    pa[i].b.setPositionY(ran);
                    pa[i].t.setPositionY(ran + config.pipeOffsetY);
                    this._crossFlag = false;
                }
                pa[i].b.setPositionX(prePos - 1.4);
                pa[i].t.setPositionX(prePos - 1.4);
                if (Math.round(prePos) - parseInt(this._birdX) <= pa[i].b.getContentSize().width && !this._crossFlag) {
                    sound.playPointSound();
                    this._score++;
                    this._crossFlag = true;
                }
                //碰撞检测
                if (this.collide(bird, pa[i].b) || this.collide(bird, pa[i].t)) {
					sound.playDieSound();
                    this._die = true;
                }
            }
            this.setScore();
        } else {
            if (!this._allOverFlag) {
                this.gameOver();
            }
        }
    },
    collide: function(a, b){
        var ap = a.getPosition(), as = a.getContentSize(), bp = b.getPosition(), bs = b.getContentSize();
        var aRect = a.getBoundingBoxToWorld();
        var bRect = b.getBoundingBoxToWorld();
        return cc.rectIntersectsRect(aRect, bRect);
    },
    gameOver: function(){
        var bird = this._bird;
        bird.cleanup();
        bird.runAction(Animate.birdFall());
        bird.runAction(cc.MoveBy.create(0.5, cc.p(0, -(bird.getPositionY() - 120))));
        sound.playHitSound();
        this._ground.cleanup();
        config.setScore(this._score);
        this._scoreSprite.removeFromParent(true);
        this.addChild(GameOver.create(this), 99);
        this._allOverFlag = true;
    },
    up: function(){
        sound.playWingSound();
		this._v = 40;
        var bird = this._bird;
        
        bird.cleanup();
        bird.runAction(Animate.birdFly(config.birdType));
        bird.runAction(Animate.birdUp(cc.CallFunc.create(function(){
            bird.runAction(Animate.birdFall());
        })));
    },
    pipeArray: null,
    addPipe: function(){
        var pipe = cc.Node.create();
        this.pipeArray = new Array();
        pipe.setPosition(cc.p(0, 112));
        for (var i = 0; i < 3; i++) {
            var pb = cc.Sprite.create(s_pipe_bottom);
            var pt = cc.Sprite.create(s_pipe_top);
            var positionX = config.pipeOffsetX * i + config.width * 2;
            var ran = this.randomBottom();
            pb.setAnchorPoint(cc.p(1, 1));
            pt.setAnchorPoint(cc.p(1, 0));
            pb.setPosition(positionX, ran);
            pt.setPosition(positionX, ran + config.pipeOffsetY);
            pipe.addChild(pb);
            pipe.addChild(pt);
            this.pipeArray.push({
                b: pb,
                t: pt
            });
        }
        this.addChild(pipe);
    },
    onMouseUp: function(event){
        this.onTouch(event);
    },
    onTouchesEnded: function(touches, event){
        if (touches.length <= 0) 
            return;
        var touch = touches[0];
        this.onTouch(touch);
    },
    onTouch: function(event){
        if (!this._start) {
            this.onStart();
        }
        if (!this._die && this._start && this._in) {
            this.up();
            this._t = 0;
        }
    }
});

StartLayer.create = function(){
    var sl = new StartLayer();
    if (sl && sl.init()) {
        return sl;
    }
    return null;
}

StartLayer.scene = function(){
    var scene = cc.Scene.create();
    var layer = StartLayer.create();
    scene.addChild(layer);
    return scene;
}
